package com.example.actionsignin.mvp.view;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.actionsignin.R;
import com.example.actionsignin.entity.LoginEntity;
import com.example.actionsignin.http.HttpUtil;
import com.example.actionsignin.utils.FileUtil;
import com.example.actionsignin.utils.ToastUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 注册界面
 */
public class EnrollActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "EnrollActivity";
    private EditText mName;
    private EditText mSchool;
    private EditText mPhone;
    private EditText mNumber;
    private EditText mPassword;
    private ImageView mHead;

    private String mPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enroll);

        init();
    }

    private void init() {
        findViewById(R.id.enroll_btn).setOnClickListener(this);
        findViewById(R.id.activity_enroll_up).setOnClickListener(this);

        mName = (EditText) findViewById(R.id.activity_enroll_name);
        mPhone = (EditText) findViewById(R.id.activity_enroll_phone);
        mSchool = (EditText) findViewById(R.id.activity_enroll_school);
        mNumber = (EditText) findViewById(R.id.activity_enroll_school_num);
        mPassword = (EditText) findViewById(R.id.activity_enroll_password);
        mHead = (ImageView) findViewById(R.id.activity_enroll_head);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id)
        {
            case R.id.enroll_btn:
                String name = mName.getText().toString();
                String phone = mPhone.getText().toString();
                String school = mSchool.getText().toString();
                String number = mNumber.getText().toString();
                String password = mPassword.getText().toString();
                if (!name.equals("") && !phone.equals("") && !school.equals("") && !number.equals("") && !password.equals("") && !mPath.equals(""))
                {
                    setData(name,phone,school,number,password,mPath);
                }else {
                    ToastUtil.INSTANCE(this,"请完善信息!");
                }
                break;
                case R.id.activity_enroll_up:
                    initPermission();
                    break;
        }
    }

    private void setData(String name, String phone, String school, String number,String password,String path) {
//        Map<String,String> map = new HashMap<>();
//        map.put("name",name);
//        map.put("telephone",phone);
//        map.put("school",school);
//        map.put("snumber",number);
//        map.put("password",password);

        File file = new File(path);
        RequestBody body = MultipartBody.create(MediaType.parse("image/jpg"),file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("image",file.getName(),body);

        HttpUtil.onSend().onEnroll(name,phone,school,number,password,part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull LoginEntity loginEntity) {
                        if (loginEntity.getResult().equals("1"))
                        {
                            toEntry();
                        }else {
                            ToastUtil.INSTANCE(getApplicationContext(),"注册失败!");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d(TAG, "onError: " + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void toEntry()
    {
        Intent intent = new Intent(EnrollActivity.this,EntryActivity.class);
        startActivity(intent);
        finish();
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            {
                ActivityCompat.requestPermissions(EnrollActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }else {
                initCameraPermission();
            }
        }else {
            initCameraPermission();
        }
    }

    private void initCameraPermission()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
            {
                ActivityCompat.requestPermissions(EnrollActivity.this,new String[]{Manifest.permission.CAMERA},2);
            }else {
                openCamera();
            }
        }else {
            openCamera();
        }
    }

    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("camerasensortype",2);
        intent.putExtra("autofocus",true);
        intent.putExtra("fullScreen",false);
        intent.putExtra("showActionIcons",false);
        mPath = FileUtil.getFileName();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPath)));
        startActivityForResult(intent,1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {
            case 1:
                mPath = FileUtil.WritePhoto(mPath);
                Glide.with(this).load(mPath).into(mHead);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @android.support.annotation.NonNull String[] permissions, @android.support.annotation.NonNull int[] grantResults) {
        switch (requestCode)
        {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    initCameraPermission();
                }else {
                    ToastUtil.INSTANCE(this,"无权限，请打开摄像头！");
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    openCamera();
                }else {
                    ToastUtil.INSTANCE(this,"无权限，请打开摄像头！");
                }
                break;
        }
    }
}
